package com.nowcoder.controller;

import com.nowcoder.entity.Comment;
import com.nowcoder.entity.DiscussPost;
import com.nowcoder.entity.Page;
import com.nowcoder.service.ElasticsearchService;
import com.nowcoder.service.LikeService;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SearchController implements CommunityConstant {
    @Autowired
    ElasticsearchService elasticsearchService;

    @Autowired
    UserService userService;

    @Autowired
    LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) {
        SearchPage<DiscussPost> searchHits = elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());
        // 聚合结果
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        for(SearchHit<DiscussPost> post: searchHits) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("post", post.getContent());
            map.put("user", userService.findUserById(post.getContent().getUserId()));
            map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getContent().getId()));
            discussPosts.add(map);
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        page.setPath("/search?keyword=" + keyword);
        page.setRows(searchHits == null ? 0 : (int) searchHits.getTotalElements());

        return "/site/search";
    }
}
